package com.ship.auth.controller;

import com.ship.auth.bean.UnifyData;
import com.ship.auth.service.SysLoginService;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.security.service.TokenService;
import com.ship.system.api.model.LoginUser;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

@RequestMapping("/unify")
@RestController
@CrossOrigin
public class AesTokenController {

    private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String SECRET_KEY = "zaS2A9br8H6oJGDC"; // 16 字节的密钥
    private static final String INIT_VECTOR = "nPqJnRlEbJnYeZjZ";  // 16 字节的初始化向量

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private TokenService tokenService;

    /**
     * 期现一体化 解密
     * @param unifyData
     * @return
     */
    @PostMapping("/ProEncryptedInfo")
    public JsonResult authenticationLogin(@RequestBody UnifyData unifyData) {
        try {
            // 对 Account 进行加密并将结果与 Token 比较
            String encryptedAccount = aes_encrypt(unifyData.getAccount(), SECRET_KEY);
            if (encryptedAccount.equalsIgnoreCase(unifyData.getToken())) {

                LoginUser userInfo = sysLoginService.loginUnify(unifyData.getAccount());
                return JsonResult.success(tokenService.createToken(userInfo));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.failed("登录失败");
    }

//    @PostMapping("/EncryptAccount")
//    public String encryptAccount(@RequestBody UnifyData unifyData) {
//        try {
//            return encryptAES(unifyData.getAccount(), SECRET_KEY);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "加密失败";
//        }
//    }

//    private String encryptAES(String data, String secretKey) throws Exception {
//        Key key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
//        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
//        IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
//        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
//        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
//        return Base64.getEncoder().encodeToString(encryptedData);
//    }



    public static String aes_encrypt(String content, String strKey) {
        try {
            byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
            SecretKey key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] cleartext = content.getBytes("UTF-8");
            byte[] ciphertextBytes = cipher.doFinal(cleartext);
            return new String(Hex.encodeHex(ciphertextBytes)).toUpperCase();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String aes_decrypt(String encryptResult, String strKey) {
        try {
            byte[] keyBytes = Arrays.copyOf(strKey.getBytes("ASCII"), 16);
            SecretKey key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] cleartext = Hex.decodeHex(encryptResult.toCharArray());
            byte[] ciphertextBytes = cipher.doFinal(cleartext);
            return new String(ciphertextBytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (DecoderException e) {
            e.printStackTrace();
        }
        return null;
    }

}
